import json
from django.http import HttpResponse
from booking.models import User,Orders
import requests
from datetime import date, datetime,timedelta
import os
from django.conf import settings
from django.core.cache import cache

def userupdate(request):
    if request.method == 'POST':
        uid = request.POST.get('uid')
        name = request.POST.get('name')
        emall = request.POST.get('emall')
        phone = request.POST.get('phone')
        image = request.FILES.get('image')
        user = User.objects.filter(openid = uid)
        print(uid,emall,phone)
        if image and user:
            user = user.first()
            file_info, suffix = os.path.splitext(image.name)
            print(suffix)
            image.name = uid + suffix
            if suffix.upper() not in ['.JPG', '.JPEG', '.PNG']:
                return HttpResponse(json.dumps({"ret":'F1'}))
            savename = os.path.join(os.getcwd(),'static')
            savename = os.path.join(savename,image.name)
            if image:
                with open(savename,'wb') as f:
                    f.write(image.read())
            photo = "https://www.stringzc.top/static/" + image.name
            user.photo = photo
            print(user.photo)
            user.phone = phone
            st = 0
            if name:
                user.name = name
                st = 2
            if emall:
                user.emall = emall
                st += 1
            user.save()
            if st == 0:
                return HttpResponse(json.dumps({"ret":'F2',"photo":photo}))
            elif st == 1:
                return HttpResponse(json.dumps({"ret":'F2',"photo":photo})) 
            else:
                return HttpResponse(json.dumps({"ret":'F3',"photo":photo,"name":name}))


def getbooks(request):
    data = json.loads(request.body)
    openid = data['openid']
    lists = Orders.objects.filter(uid=openid)
    times = []
    if cache.get(openid):
        ti = cache.get('ctime')
        times.append({'times':ti})
    if lists:
        for i in lists:
            times.append({'times':str(i.times).split()[0]})
    return HttpResponse(json.dumps({"ret":"True","books":times}))
